#!/usr/bin/env bash
# a wrapper to launch lemonade on every monitor, as determined by bspwm
# note: this has to be bash or it won't die correctly..
# todo: understand ^

echo -e -n "
==== ==== ==== ==== ==== \033[1;33m
 ,.        ,.        ,.
(:;)      (:;)      (:;)
 \`'        \`'        \` \e[0m
==== ==== ==== ==== ===="

error() {
   local sourcefile=$1
   local lineno=$2
   echo err: $sourcefile $lineno
}
trap 'error "${BASH_SOURCE}" "${LINENO}"' ERR

export -f error

# todo: reconsider this, is the different between juicer
# being main config point and themes passing into lemons..
# note: some scripts may rely on variables from here, eg icon
set -a
eval "$(theme get)"


# only need this for p_gap and b_border_width values.
# relevance
cd $(dirname $([ -L $0  ] && readlink -f $0 || echo $0))
export PATH=$PATH:`pwd`/tools

gapped=$(iif "[ ! $(bspc config window_gap) -le 0 ]")
eval bspc config ${p_position}_padding \
     $(iif $gapped $((p_height+p_gap)) $((p_height+b_border_width)) )

i=0

# note: mon will be available to all lemons as reference.
for mon in $(bspc query -M); do
	i=$(($i+1))
	conf=`ls juicers | sed -n "$i p"`
	[ -z "$conf" ] && conf=`ls juicers | sed -n "1 p"`

	tools/lemonade "$conf" &
  lemonade_ids=$'\n'"$!$lemonade_ids"
done


set_refresh() {
    trap "eval bspc config ${p_position}_padding $(iif $gapped 0 $b_border_width); trap - TERM; kill 0;" INT TERM QUIT


    if ! $init; then
        for id in $lemonade_ids; do
            kill -USR1 $id
        done
    fi

    trap set_refresh USR1
    init=false
    wait
}

init=true
echo $$ > /tmp/panel-pid
set_refresh

# where are we?

#wait
